package com.bbs.action;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.bbs.comm.SessionContext;
import com.bbs.dao.UserDao;
import com.bbs.dao.impl.UserDaoImpl;
import com.bbs.model.User;
import com.bbs.util.EncrypterUti;

/**
 * 
 * @author Administrator
 * 
 */
public class LoginAction extends BaseAction {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private User user;
	
	//前台登陆
	public String userLogIn() throws IOException {
		logIn();
		return "userLogIn";
	}
	
	//后台登陆
	public String adminLogIn() throws IOException {
		logIn();
		return "adminLogIn";
	}

	/**
	 * 登陆逻辑
	 * 
	 * @throws IOException
	 */
	public void logIn() throws IOException {
		logger.info(user.getUser_name() + "尝试登陆");
		user=identify(user);
		if (null==user) {
			logger.warn("登陆失败");
		}
		setSessionContext();
	}

	/**
	 * 验证身份
	 * 
	 * @param user
	 * @return
	 * @throws IOException
	 */
	public User identify(User user) throws IOException {
		UserDao userDao = new UserDaoImpl();
		User userNice = userDao.logIn(user);
		if (EncrypterUti.verify(userNice.getUser_password(), user.getUser_password())) {
			return  userNice;
		}
		return null;
	}
       
	/**
	 * 为sessionContext初始化
	 */
	private void setSessionContext() {
		SessionContext context = SessionContext.getSessionContext();// 获取已经有的实例
		if (null == context) {// 当没有sessioncontext实例时候
			HttpSession session = ServletActionContext.getRequest()
					.getSession();
			context = new SessionContext();
			context.regist(session);
		}
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		context.setLoginTime(dateFormat.format(new Date()));
		context.setUser(user);
		context.setUserIP(getRequest().getRemoteAddr());
	}
	//退出登录
	public String logOut() {
		HttpSession session = null;
		//获得当前request
		HttpServletRequest req = ServletActionContext.getRequest();
		if(req!=null){
			session = req.getSession(false);//获得当前session
		}
		 
		try {
			if(session!=null){
				session.invalidate();//销毁当前session
			}
		} catch (Exception e) {
			logger.info("Session 已经销毁");
			e.printStackTrace();
		}
		return "logOut";
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}
}
